//
// Created by zhku666 on 25-2-24.
//
#include <cstdio>
#include <mutex>
#include <windows.h>
#include <unistd.h>
#include "log.cpp"
#include "lock.cpp"

void add_cattle();
void delete_cattle();
void select_cattle();
void located_cattle();

bool judge_cattle_id(char cattle_id[100]) {
    FILE *file = fopen("cattle.txt", "r");
    if (file == NULL) {
        fclose(file);
        printf("打开文件失败\n");
        return true;
    }

    char line[100];

    // 遍历文件，检查cattle_id是否存在
    while (fgets(line, sizeof(line), file)) {
        char id[100];
        sscanf(line, "%[^-]", id); // 提取cattle_id部分
        if (strcmp(id, cattle_id) == 0) {
            fclose(file);
            //找到重复的就返回false
            return true;
        }
    }
    fclose(file);
    return false;
}


void add_cattle()
{
    char cattle_id[100];
    char year[100];
    printf("请输入牛的id\n");
    scanf("%s", &cattle_id);
    printf("请输入牛的出生年份\n");
    scanf("%s", &year);
    //判定id是否存在
    if (!judge_cattle_id(cattle_id))
    {
        //写入txt
        FILE *file = fopen("cattle.txt", "a"); // 以追加模式打开文件
        if (file == NULL) {
            perror("打开文件失败\n");
            return;
        }
        // 格式化输出，sensor_id输出为NULL
        fprintf(file, "%s-%s-%s\n", cattle_id, year, "NULL");

        fclose(file);

        char logMessage[200];
        sprintf(logMessage, "添加牛只成功，id为:%s", cattle_id);
        log(logMessage);

    }else
    {
        printf("牛的id已存在！\n");
        char logMessage[200];
        sprintf(logMessage, "添加牛只失败，id为:%s", cattle_id);
        log(logMessage);
    }

}

void delete_cattle()
{
    char cattle_id[100];
    printf("请输入牛的id\n");
    scanf("%s", &cattle_id);

    // 调用judge_id_exit函数判断cattle_id是否存在
    if (!judge_cattle_id(cattle_id)) {
        printf("不存在id为%s的牛\n", cattle_id);

        char logMessage[200];
        sprintf(logMessage, "该牛不存在，删除牛只失败，id为:%s", cattle_id);
        log(logMessage);
        return;
    }

    // 如果cattle_id存在，进行删除操作
    FILE *file = fopen("cattle.txt", "r");
    if (file == NULL) {
        perror("打开文件失败\n");
        return;
    }

    FILE *tempFile = fopen("temp.txt", "w");
    if (tempFile == NULL) {
        perror("打开文件失败\n");
        fclose(file);
        return;
    }

    char line[100];
    while (fgets(line, sizeof(line), file)) {
        char id[100];
        sscanf(line, "%[^-]", id); // 提取cattle_id部分

        if (strcmp(id, cattle_id) != 0) {
            // 将不匹配的记录写入临时文件
            fprintf(tempFile, "%s", line);
        }
    }

    fclose(file);
    fclose(tempFile);

    // 删除原文件，并将临时文件重命名为原文件
    remove("cattle.txt");
    rename("temp.txt", "cattle.txt");

    char logMessage[200];
    sprintf(logMessage, "删除牛只成功，id为:%s", cattle_id);
    log(logMessage);
}


void select_cattle()
{
    FILE *file = fopen("cattle.txt", "r");
    if (!file) {
        printf("打开文件失败\n");
        return;
    }

    char line[100];
    int recordCount = 0; // 用于统计记录数

    // 打印标题行
    printf("牛id\t年份\t传感器id\n");

    while (fgets(line, sizeof(line), file)) {
        char cattle_id[100];
        char sensor_id[100];
        char year[100];

        // 去掉换行符
        line[strcspn(line, "\n")] = '\0';

        // 解析每行数据
        sscanf(line, "%[^-]-%[^-]-%s", cattle_id, year, sensor_id);

        // 打印数据，字段之间用制表符分隔
        printf("%s\t%s\t%s\n", cattle_id, year, sensor_id);

        recordCount++;
    }

    fclose(file);

    printf("共有%d条数据\n", recordCount);

    char logMessage[200];
    sprintf(logMessage, "查询牛只，牛数为:%d", recordCount);
    log(logMessage);
}

void print_cattle_location(const char *cattle_id) {
    FILE *cattle_file = fopen("cattle.txt", "r");
    if (!cattle_file) {
        perror("无法打开cattle.txt");
        return;
    }

    char line[256];
    char sensor_id[256] = {0};
    while (fgets(line, sizeof(line), cattle_file)) {
        char current_cattle_id[256];
        sscanf(line, "%[^-]-%*[^-]-%s", current_cattle_id, sensor_id);
        if (strcmp(current_cattle_id, cattle_id) == 0) {
            break;
        }
        sensor_id[0] = '\0'; // 重置 sensor_id
    }
    fclose(cattle_file);

    if (sensor_id[0] == '\0') {
        printf("牛ID不存在或未绑定传感器\n");
        return;
    }

    FILE *sensor_file = fopen("sensor.txt", "r");
    if (!sensor_file) {
        perror("无法打开sensor.txt");
        return;
    }

    while (fgets(line, sizeof(line), sensor_file)) {
        char current_sensor_id[256];
        int longitude, latitude;
        sscanf(line, "%[^-]-%*[^-]-%d-%d", current_sensor_id, &longitude, &latitude);
        if (strcmp(current_sensor_id, sensor_id) == 0) {
            printf("经度: %d, 纬度: %d\n", longitude, latitude);
            fclose(sensor_file);
            return;
        }
    }
    fclose(sensor_file);

    printf("未找到传感器的经纬度信息\n");
}

// 持续追踪牛的定位
void located_cattle()
{
    char cattle_id[100];
    printf("请输入牛的id\n");
    scanf("%99s", cattle_id); // 防止输入溢出

    while (true) { // 无限循环
        get_lock();
        system("cls");
        print_cattle_location(cattle_id);
        unlock();
        sleep(1); // 延时
    }
}

void cattle()
{
    int input=0;
    while (true)
    {
        printf("--------------牛--------------\n");
        printf("1.添加牛\n");
        printf("2.删除牛\n");
        printf("3.查询牛\n");
        printf("4.追踪牛\n");
        printf("输入其他返回\n");
        scanf_s("%d",&input);
        switch (input)
        {
        case 1:
            add_cattle();
            break;
        case 2:
            delete_cattle();
            break;
        case 3:
            select_cattle();
            break;
        case 4:
            located_cattle();
            break;
        default:
            return;
        }
    }
}
